package com.wonsec.useragent.aspect;

import com.wonsec.useragent.entity.ChannelTracking;
import com.wonsec.useragent.repository.ChannelTrackingRepository;
import com.wonsec.useragent.utils.ChannelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author： mzy
 * @Date： 2025/5/13 下午2:42
 * @Describe：
 */
@Component
public class ChannelTrackingInterceptor implements HandlerInterceptor {

    @Autowired
    private ChannelTrackingRepository channelTrackingRepository;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String channel = ChannelUtils.detectChannel(request);
        String channelDetail = ChannelUtils.detectChannelDetail(request);

        ChannelTracking tracking = new ChannelTracking();

        tracking.setChannel(channel);
        tracking.setChannelDetail(channelDetail);
        tracking.setUserAgent(request.getHeader("User-Agent"));
        tracking.setIpAddress(ChannelUtils.getClientIp(request));
        tracking.setSessionId(request.getSession().getId());
        tracking.setLandingPage(request.getRequestURI());

        //TODO 在此可存入用户id之类的数据

        channelTrackingRepository.save(tracking);

        // 存入Session供后续使用
        request.getSession().setAttribute("access_channel", channel);
        return true;
    }

}
